package org.example.trade.listener;

import com.alibaba.fastjson2.JSON;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.example.api.order.OrderFacadeService;
import org.example.api.order.constant.TradeOrderState;
import org.example.api.order.model.TradeOrderVO;
import org.example.api.order.request.OrderCreateAndConfirmRequest;
import org.example.api.order.response.OrderResponse;
import org.example.base.response.SingleResponse;
import org.example.trade.application.TradeApplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lly
 */
@Component
public class OrderCreateTransactionListener implements TransactionListener {

    private static final Logger logger = LoggerFactory.getLogger(OrderCreateTransactionListener.class);

    @Autowired
    private TradeApplicationService tradeApplicationService;
    @Autowired
    private OrderFacadeService orderFacadeService;

    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            OrderCreateAndConfirmRequest orderCreateAndConfirmRequest = JSON.parseObject(JSON.parseObject(message.getBody()).getString("body"), OrderCreateAndConfirmRequest.class);

            //在redis中做库存的扣减
            OrderResponse orderResponse = tradeApplicationService.newBuyPlus(orderCreateAndConfirmRequest);
            return orderResponse.getSuccess() ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;

        } catch (Exception e) {
            logger.error("executeLocalTransaction error, message = {}", message, e);
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        OrderCreateAndConfirmRequest orderCreateAndConfirmRequest = JSON.parseObject(JSON.parseObject(new String(messageExt.getBody())).getString("body"), OrderCreateAndConfirmRequest.class);

        SingleResponse<TradeOrderVO> response = orderFacadeService.getTradeOrder(orderCreateAndConfirmRequest.getOrderId());

        //如果订单已经创建成功，则直接返回。不再需要做废单处理了。
        if (response.getSuccess() && response.getData() != null && response.getData().getOrderState() == TradeOrderState.CONFIRM) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }

        return LocalTransactionState.ROLLBACK_MESSAGE;
    }
}
